package com.example.scanfast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.room.Room;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.widget.SearchView;
import android.widget.Toast;


import com.example.scanfast.adapter.PagerAdapter;
import com.example.scanfast.bean.FileBean;
import com.example.scanfast.constant.Constant;
import com.example.scanfast.database.FileDataBase;
import com.example.scanfast.fragment.ExampleFragment;

import com.example.scanfast.receiver.MyBroadcastReceiver;
import com.example.scanfast.service.MediaFilesObserverService;
import com.example.scanfast.thread.MyThreadPool;
import com.example.scanfast.thread.SingletonThreadPool;
import com.example.scanfast.utils.CommonUtil;
import com.google.android.material.tabs.TabLayout;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;

import java.util.ArrayList;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class MainActivity extends AppCompatActivity {

    private final String[] typeList = {"ALL", "PDF", "PPTX", "DOCX", "XLSX", "ETT", "MP3", "MP4", "JPG"};
    private final Integer[] iconList = {R.mipmap.pdf, R.mipmap.ppt, R.mipmap.doc, R.mipmap.excel, R.mipmap.ett, R.mipmap.mp3, R.mipmap.mp4, R.mipmap.image};

    //定义图标集合
    // 存储文件信息的哈希表
    private final ConcurrentHashMap<String, List<FileBean>> hashMap = new ConcurrentHashMap<>();
    private TabLayout tabLayout;
    private ViewPager viewPager;

    static MyThreadPool threadPool = new MyThreadPool();

    private boolean isScan = true;
    private boolean isGranted = false;

    private Handler handler = new Handler();

    private List<String> pathList = new ArrayList<>();

    private FileDataBase fileDataBase;
    private volatile List<FileBean> mergeList = new ArrayList<>(); // 将 mergeList 提升为类的成员变量
    private List<FileBean> fileBeanList;
    private CountDownLatch countDownLatch;
    private PagerAdapter adapter;
    private List<FileBean> list;

    private ExampleFragment.FileAdapter fileAdapter;



    private MediaFilesObserverService mediaFilesObserver;


    @SuppressLint({"MissingInflatedId", "UnspecifiedRegisterReceiverFlag"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileDataBase = Room.databaseBuilder(this, FileDataBase.class, "file").build();
        //获取对应的控件
        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.view_pager);

        requestStoragePermission();

        // 在需要启动服务的地方调用以下代码
        Intent serviceIntent = new Intent(this, MediaFilesObserverService.class);
        this.startService(serviceIntent);

        startScheduledTask();
    }

    private void checkDatabaseAndInitializeAdapter() {
        // 检查数据库数据
        threadPool.getExecutorService().submit(() -> {
            fileBeanList = fileDataBase.fileDao().findAll();
            if (fileBeanList.size() > 0 && isScan) {
                queryByDatabase();
            } else {
                scan();
            }
        });
    }





    private void scan() {
        countDownLatch = new CountDownLatch(1);
        commonScan();
        try {
            countDownLatch.await(); // 等待媒体库扫描和磁盘扫描完成

            threadPool.getExecutorService().submit(new Runnable() {
                @Override
                public void run() {
                    fileDataBase.fileDao().insertBatch(mergeList);
                }
            });

            queryByMediaStore();
            isScan = false;

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    //请求权限
    private void requestStoragePermission() {
        //安卓版本大于6小于11采用弹窗申请方式,存储权限变成了特殊权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                isGranted = true;
                checkDatabaseAndInitializeAdapter();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            }
        }
        //获取安卓的版本,如果大于等于11,采用意图申请方式，存储权限变成了危险权限
        else {
            if (Environment.isExternalStorageManager()) {
                isGranted = true;
                checkDatabaseAndInitializeAdapter();

            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, 1);
            }
        }
    }






    //扫描媒体库和磁盘
    @SuppressLint({"Range", "SetTextI18n"})
    public class ScanMediaAndDisk implements Runnable {
        @Override
        public void run() {
            //扫描媒体库
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                try {
                    fileBeanList = CommonUtil.scanMediaStore(MainActivity.this, hashMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mergeList.addAll(fileBeanList);
            for (FileBean fileBean : fileBeanList) {
                pathList.add(fileBean.getPath());
            }
            // 扫描磁盘
            CommonUtil.FileSearcher fileSearcher = new CommonUtil.FileSearcher(hashMap, typeList, iconList);
            try {
                List<FileBean> fileBeanList = CommonUtil.FileSearcher.searchFiles(new File(Environment.getExternalStorageDirectory().getPath()));

                Log.d(Constant.TAG, "磁盘扫描完成: " + fileBeanList.size());
                for (FileBean fileBean : fileBeanList) {
                    if (!pathList.contains(fileBean.getPath())) {
                        mergeList.add(fileBean);
                        List<FileBean> list = hashMap.computeIfAbsent(fileBean.getFileType(), k -> new ArrayList<>());
                        list.add(fileBean);
                    }
                }
                Log.d(Constant.TAG, "mergeList: " + mergeList.size());
                CommonUtil.sendDatabaseQueryNotification(mergeList.size(), MainActivity.this);
                countDownLatch.countDown();


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    isGranted = true;
                    // 开始磁盘扫描
                    scan();

                } else {
                    Toast.makeText(this, "请先授权", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // 检查 requestCode 是否与你之前的权限请求代码一致
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了所请求的权限，可以执行相应操作
                checkDatabaseAndInitializeAdapter();
            } else {
                // 权限被拒绝，可以向用户解释权限的重要性，或者提供其他处理方式
                // 例如，显示一个提示或者禁用相关功能
                CommonUtil.showPermissionRationale(MainActivity.this);
            }
        }
    }

    private ExampleFragment createExampleFragment(String fileType, List<FileBean> fileList) {
        Bundle bundle = new Bundle();
        ExampleFragment exampleFragment = new ExampleFragment();

        bundle.putSerializable(Constant.FILE_LIST_KEY, (Serializable) fileList);
        exampleFragment.setArguments(bundle);

        adapter.addFragment(exampleFragment, fileType);
        return exampleFragment;
    }
    //从媒体库和磁盘查询数据
    private void queryByMediaStore() {
        adapter = new PagerAdapter(getSupportFragmentManager());
        for (String s : typeList) {
            List<FileBean> fileList = null;
            if (!s.equals("ALL")) {
                fileList = hashMap.get(s.toLowerCase());
                Log.d(Constant.TAG, "我是媒体库查询的: "+fileList);
            } else {
                fileList = new ArrayList<>(mergeList);
            }
            createExampleFragment(s, fileList);

        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initViewAndEvent();

            }
        });
    }
    //从数据库查询数据
    private void queryByDatabase() {

        adapter = new PagerAdapter(getSupportFragmentManager());
        for (String s : typeList) {
            List<FileBean> fileList;
            if (!s.equals("ALL")) {
                fileList = fileDataBase.fileDao().findByFileType(s.toLowerCase());
                Log.d(Constant.TAG, "我是数据库查询的: "+fileList);

            } else {
                fileList = new ArrayList<>(fileBeanList);
            }

            createExampleFragment(s, fileList);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initViewAndEvent();

            }
        });
    }

    private void initViewAndEvent(){

        viewPager.setAdapter(adapter);
        adapter.notifyDataSetChanged(); // 更新适配器数据
        tabLayout.setupWithViewPager(viewPager);
    }





    //定义一个扫描的公共方法
    public void commonScan(){
        SingletonThreadPool singletonThreadPool = SingletonThreadPool.getInstance();

        singletonThreadPool.executeTask(new ScanMediaAndDisk());

        // 在所有任务执行完成后，关闭线程池
        singletonThreadPool.shutdown();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            if (fragment instanceof  ExampleFragment){
                ((ExampleFragment) fragment).clearData();
            }
        }
        adapter.clearData();

        tabLayout.clearOnTabSelectedListeners();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);
        SearchView searchView = (SearchView) menu.findItem(R.id.serach).getActionView();
        assert searchView != null;
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Log.d(Constant.TAG, "s: "+s);
                return true;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }


    private void startScheduledTask() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 19);
        calendar.set(Calendar.MINUTE, 37);
        calendar.set(Calendar.SECOND, 15);

        if (alarmManager != null) {
            long triggerTime = calendar.getTimeInMillis();
            long repeatInterval = AlarmManager.INTERVAL_DAY; // 一天的毫秒数

            // 设置闹钟
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, repeatInterval, pendingIntent);
        }
    }






}